package com.luoling.oa.oaSync.service.impl;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.luoling.oa.oaSync.domian.DataType;
import com.luoling.oa.oaSync.domian.DecryptionModel;
import com.luoling.oa.oaSync.domian.Department;
import com.luoling.oa.oaSync.domian.EmployeeInfo;
import com.luoling.oa.oaSync.service.OaSyncService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.util.List;

/**
 * Description:
 * Copyright:   Copyright (c)2024
 * Company:
 *
 * @author: 张李鑫
 * @version: 1.0
 * Create at:   2024-12-17 14:11:02
 * <p>
 * Modification History:
 * Date         Author      Version     Description
 * ------------------------------------------------------------------
 * 2024-12-17     张李鑫                     1.0         1.0 Version
 */
@Service
public class OaSyncServiceImpl implements OaSyncService {

    private static final Logger log = LoggerFactory.getLogger(OaSyncServiceImpl.class);
    @Autowired
    private ObjectMapper objectMapper;

    String key = "7XlPHxLSATXwkpmWvaovAw==";

    @Override
    public void sync(String data) throws Exception {
        log.info("data:{}", data);
        DecryptionModel decryption = decryption(data);
        Integer dataType = decryption.getDataType();
        String dataList = decryption.getData();
        if (DataType.DEPARTMENT.getValue().equals(dataType)) {
            List<Department> departments = objectMapper.readValue(dataList, new TypeReference<List<Department>>() {
            });
            log.info("departments:{}", departments);
        } else if (DataType.EMPLOYEE_INFO.getValue().equals(dataType)) {
            List<EmployeeInfo> employeeInfos = objectMapper.readValue(dataList, new TypeReference<List<EmployeeInfo>>() {
            });
            log.info("employeeInfos:{}", employeeInfos);
        }
    }

    public DecryptionModel decryption(String data) throws Exception {
        SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(), "AES");
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        IvParameterSpec ivParameterSpec = new IvParameterSpec(key.getBytes());
        cipher.init(Cipher.DECRYPT_MODE, secretKey, ivParameterSpec);
        byte[] bytes = cipher.doFinal(data.getBytes());
        String s = new String(bytes);
        log.info("接收数据" + s);
        return new DecryptionModel();
    }
}
